package com.yitiao.socket.chatroom.aio;

import com.yitiao.socket.chatroom.CommonConst;
import lombok.Data;
import lombok.SneakyThrows;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.Map;

@Data
public class ClientChatHandler implements CompletionHandler<Integer, ByteBuffer> {
    private AsynchronousSocketChannel clientChannel;

    private AioChatServer aioChatServer;

    public ClientChatHandler(AsynchronousSocketChannel channel, AioChatServer aioChatServer) {
        this.clientChannel = channel;
        this.aioChatServer = aioChatServer;
    }


    @SneakyThrows
    @Override
    public void completed(Integer result, ByteBuffer buffer) {
        if (buffer != null) {
            //buffer不为空的时候，这要执行的是read之后的回调方法
            if (result <= 0) {
                //客户端异常，将客户端从连接列表中移除
                aioChatServer.removeClient(this);
            } else {
                buffer.flip();
                String fwdMsg = aioChatServer.receive(buffer);
                System.out.println(clientChannel.getRemoteAddress() + ":" + fwdMsg);
                aioChatServer.forwardMsg(clientChannel, fwdMsg);
                buffer.clear();

                if (fwdMsg.equals(CommonConst.QUIT)) {
                    aioChatServer.removeClient(this);
                } else {
                    clientChannel.read(buffer, buffer, this);
                }
            }
        }
    }

    @Override
    public void failed(Throwable exc, ByteBuffer attachment) {

    }

}
